﻿using Harmontronics.Api.Config;
using Harmontronics.IService;
using Harmontronics.Model.Dto.Login;
using Harmontronics.Model.Dto.User;
using Harmontronics.Model.Entitys;
using Harmontronics.Model.Other;
using Harmontronics.Service;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;

namespace Harmontronics.Api.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class LoginController : ControllerBase
    {
        private IUserService _userService;
        private ICustomJWTService _jwtService;
        private IMenuService _menuService;
        private IRoleService _roleService;

        public LoginController(IRoleService roleService,IUserService userService, IMenuService menuService ,ICustomJWTService jwtService)
        {
            _roleService = roleService;
            _menuService = menuService;
            _userService = userService;
            _jwtService = jwtService;
        }
        [HttpPost]
        public ApiResponseData GetToken(LoginRequestData data)
        {
            //获取token
            var res = new ApiResponseData();
            UserRes user = _userService.GetUser(data.EmployeeNumber, data.Password);
            if (!string.IsNullOrEmpty(user.EmployeeNumber))
            {
                if(user.Enable == 0)
                {
                    res.code = 500;
                    res.message = "The current user is disabled. Contact the administrator";
                    res.data = "";
                }
                else
                {
                    res.code = 200;
                    res.message = "login success";
                    res.data = new { token = _jwtService.GetToken(user) };
                }

            }
            else
            {
                res.code = 500;
                res.message = "login failure，The account password is incorrect!";
            }
            return res;
        }
        [HttpPost]
        [Authorize]

        public ApiResponseData Info(LoginRequestData data)
        {
            var res = new ApiResponseData();
            UserReq user = _userService.GetUsersByEmp(data.EmployeeNumber);
            List<string> rolesList = _roleService.GetRoleDiscListByUserId(user.Id);
            res.data = new { username = user.UserName, roles = rolesList };
            res.code = 200;
            res.message = "Success!";
            return res;
        }
        [HttpGet]
        [Authorize]
        public ApiResponseData GetDynamicRoutes()
        {
            var res = new ApiResponseData();
            res.data = _menuService.GetAllMenus();
            res.code = 200;
            res.message = "Success!";
            return res;
        }
    }
}
